from xml.dom.minidom import parseString
import os
import glob
import sys
from wx import wx
import sqlite3
import ContentTab
import ImageTab
import LayoutTab
import TableTab
import MediaTab
import SimulationTab
import InteractionTab
import PreviewTab

# Global Variables
# ==========================
# Table Identifiers
# ==========================
# ResourceTypeTable
# 1 - Content
# 2 - Image
# 3 - Table
# 4 - Media (Audio/Video)
# 5 - Simulation (swf)
# 6 - Interaction

# StructureTypeTable
# 1 - Module
# 2 - Page
# ===========================

# Main Window/Frame Class
class WombatFrame(wx.Frame):

    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, title=title, size=(640,480))

        self.currentCourseID = -1
        self.debugMode = True
        self.database = self.GetAppPath() + "/data/Wombatdata.db"
        # check for existence of DB and if it doesn't exist, then create it.
        if not os.path.exists(self.database):
            con = sqlite3.connect(self.database)
            con.execute("CREATE TABLE CourseTable(courseID, integer primary key, courseName text)")
            con.execute("CREATE TABLE StructureTable(structureID integer primary key, courseID integer, structureTypeID integer, structureOrderNumber integer, parentID integer, structureName text)")
            con.execute("CREATE TABLE ResourceTable(resourceID integer primary key, structureID integer, resourceOrderNumber integer, resourceTypeID integer, layout text, resourceData text, courseID integer)")
            con.close()        
        self.currentContentDict = {}
        self.currentAvailableResourceDict = {}
        self.currentUsedResourceDict = {}
        self.currentImageDict = {}
        self.currentTableDict = {}
        self.currentMediaDict = {}
        self.currentSimulationDict = {}
        self.currentInteractionDict = {}
        
        self.toolbar_CREATE_COURSE = wx.NewId()
        self.toolbar_MANAGE_COURSE = wx.NewId()
        self.toolbar_PREVIEW_COURSE = wx.NewId()
        self.toolbar_PUBLISH_COURSE = wx.NewId()
        # self.bulletnumber = False
        
        # Logo on Load
        self.bitmap = wx.Bitmap("images/wombat_border_sm_solid.png")
        wx.EVT_PAINT(self, self.OnPaint)
        wx.EVT_CLOSE(self, self.OnTimeToClose)
        
        # set Default Panel on Frame
        self.Center()
        self.panel = wx.Panel(self)
        self.Bind(wx.EVT_SIZE, self._onSize)
        
        # Create Panel Creation
        
        self.courseContentPanel = wx.Panel(self.panel, -1, style=wx.SUNKEN_BORDER)
        #self.courseContentPanel.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_APPWORKSPACE))
        self.courseContentNotebook = wx.Notebook(self.courseContentPanel) # create notebook.
        courseContentSizer = wx.BoxSizer(wx.VERTICAL)
        courseContentSizer.Add(self.courseContentNotebook, 1, wx.ALL | wx.EXPAND, 0)
        self.courseContentPanel.SetSizer(courseContentSizer)
        self.courseContentPanel.Layout()
        self.courseContentPanel.Hide()
        
        wx.EVT_NOTEBOOK_PAGE_CHANGED(self, self.courseContentNotebook.GetId(), self.OnCourseContentNotebookPageChanged)
        
        # Manage Panel Creation

        self.managePanel = wx.Panel(self.panel, -1, style=wx.SUNKEN_BORDER)
        #self.managePanel.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_APPWORKSPACE))
        self.manageNotebook = wx.Notebook(self.managePanel)
        manageSizer = wx.BoxSizer(wx.VERTICAL)
        manageSizer.Add(self.manageNotebook, 1, wx.ALL | wx.EXPAND, 0)
        self.managePanel.SetSizer(manageSizer)
        self.managePanel.Layout()
        self.managePanel.Hide()
        
        wx.EVT_NOTEBOOK_PAGE_CHANGED(self, self.manageNotebook.GetId(), self.OnManageNotebookPageChanged)
        
        # Preview Panel Creation
        self.previewPanel = wx.Panel(self.panel, -1, style=wx.SUNKEN_BORDER)
        previewSizer = wx.BoxSizer(wx.VERTICAL)
        self.previewPanel.SetSizer(previewSizer)
        self.previewTab = PreviewTab.PreviewCourseTab(self.previewPanel)
        self.previewPanel.Layout()
        self.previewPanel.Hide()
        
        # Publish Panel Creation
        
        # Create Create Tabs
        self.createContentTab = ContentTab.CreateContentTab(self.courseContentNotebook)
        self.createImageTab = ImageTab.CreateImageTab(self.courseContentNotebook)
        self.createTableTab = TableTab.CreateTableTab(self.courseContentNotebook)
        self.createMediaTab = MediaTab.CreateMediaTab(self.courseContentNotebook)
        self.createSimulationTab = SimulationTab.CreateSimulationTab(self.courseContentNotebook)
        self.createInteractionTab = InteractionTab.CreateInteractionTab(self.courseContentNotebook)
                
        # Create Manage Tabs
        self.layoutContentTab = LayoutTab.LayoutContentTab(self.manageNotebook)
        
        # Create Preview Tabs
        
        # Add Tabs to Notebooks
        
        self.courseContentNotebook.AddPage(self.createContentTab, "Create Content")
        self.courseContentNotebook.AddPage(self.createImageTab, "Import Images")
        self.courseContentNotebook.AddPage(self.createTableTab, "Create Tables")
        self.courseContentNotebook.AddPage(self.createMediaTab, "Import Media")
        self.courseContentNotebook.AddPage(self.createSimulationTab, "Import Simulation")
        self.courseContentNotebook.AddPage(self.createInteractionTab, "Create Interactions")
        self.manageNotebook.AddPage(self.layoutContentTab, "Layout Resources")
        
        # Main Toolbar Creation
        
        self.toolbar = self.CreateToolBar(wx.TB_HORIZONTAL | wx.NO_BORDER | wx.TB_FLAT | wx.TB_NODIVIDER)
        self.toolbar.DoAddTool(wx.ID_NEW, "New Course", wx.Bitmap("images/newCourse.gif", wx.BITMAP_TYPE_GIF), wx.NullBitmap, 0, "New", "New Course", None)
        self.toolbar.DoAddTool(wx.ID_OPEN, "Open Course", wx.Bitmap("images/openCourse.gif", wx.BITMAP_TYPE_GIF), wx.NullBitmap, 0, "Open", "Open Course", None)
        self.toolbar.AddSeparator()
        self.toolbar.AddTool(self.toolbar_CREATE_COURSE, wx.Bitmap("images/accessories-text-editor.png", wx.BITMAP_TYPE_PNG), wx.Bitmap("images/accessories-text-editor-off.png", wx.BITMAP_TYPE_PNG), isToggle=True, shortHelpString='Create Course', longHelpString='Create Course')
        self.toolbar.AddTool(self.toolbar_MANAGE_COURSE, wx.Bitmap("images/x-office-address-book.png", wx.BITMAP_TYPE_PNG), wx.Bitmap("images/x-office-address-book-off.png", wx.BITMAP_TYPE_PNG), isToggle=True, shortHelpString="Manage Course", longHelpString="Manage Course")
        self.toolbar.AddTool(self.toolbar_PREVIEW_COURSE, wx.Bitmap("images/system-search.png", wx.BITMAP_TYPE_PNG), wx.Bitmap("images/system-search-off.png", wx.BITMAP_TYPE_PNG), isToggle=True, shortHelpString="Preview Course", longHelpString="Preview Course")
        self.toolbar.AddTool(self.toolbar_PUBLISH_COURSE, wx.Bitmap("images/package-x-generic.png", wx.BITMAP_TYPE_PNG), wx.Bitmap("images/package-x-generic-off.png", wx.BITMAP_TYPE_PNG), isToggle=True, shortHelpString="Publish Course", longHelpString="Publish Course")
        self.toolbar.AddSeparator()
        
        wx.EVT_TOOL(self, self.toolbar_CREATE_COURSE, self.SetMode)
        wx.EVT_TOOL(self, self.toolbar_MANAGE_COURSE, self.SetMode)
        wx.EVT_TOOL(self, self.toolbar_PREVIEW_COURSE, self.SetMode)
        wx.EVT_TOOL(self, self.toolbar_PUBLISH_COURSE, self.SetMode)
        wx.EVT_TOOL(self, wx.ID_NEW, self.NewCourse)
        wx.EVT_TOOL(self, wx.ID_OPEN, self.OpenCourse)
        
        self.toolbar.EnableTool(self.toolbar_CREATE_COURSE, False)
        self.toolbar.EnableTool(self.toolbar_MANAGE_COURSE, False)
        self.toolbar.EnableTool(self.toolbar_PREVIEW_COURSE, False)
        self.toolbar.EnableTool(self.toolbar_PUBLISH_COURSE, False)
        
        self.toolbar.Realize()
        
        # Set Open Course Enabled Status
        con = sqlite3.connect(self.database)
        cur = con.cursor()
        cur.execute("SELECT courseID from CourseTable")
        if(cur.fetchone() is None):
            self.toolbar.EnableTool(wx.ID_OPEN, False)
            self.DisplayDebug("if courses exist, enable open course")
        else:
            self.toolbar.EnableTool(wx.ID_OPEN, True)
        con.close()        
        
        # Set Application Icon
        appIcon = wx.Icon("images/wombat_32.ico", wx.BITMAP_TYPE_ICO, 16, 16)
        self.SetIcon(appIcon)
        
        # Show the Application Frame
        self.panel.Hide()
        self.Show(True)
    
    # Create Event Function
    def OnCourseContentNotebookPageChanged(self, event):
        # determine which page is clicked, if its self.layoutcontenttab, then refresh available resources here...
        if(self.courseContentNotebook.IsShown() == True):
            if (self.courseContentNotebook.GetSelection() == 0): # content tab
                self.DisplayDebug("do something here..., if necessary")
            elif (self.courseContentNotebook.GetSelection() == 1): # image tab
                self.DisplayDebug("create/manage image stuff here")
            elif (self.courseContentNotebook.GetSelection() == 2): # table tab
                self.DisplayDebug("create/manage table stuff here")
            elif (self.courseContentNotebook.GetSelection() == 3): # media tab
                self.DisplayDebug("create/manage media stuff here")
            elif (self.courseContentNotebook.GetSelection() == 4): # simulation tab
                self.DisplayDebug("create /manage sim stuff here")
            
            if(self.courseContentNotebook.GetSelection() != 3): # not media, stop it
                if(len(self.createMediaTab.mediaPanel.GetChildren()) > 0):
                    self.createMediaTab.mediaPlayer.Stop()
            if(self.courseContentNotebook.GetSelection() != 4): # not simulation, stop it
                self.DisplayDebug("manage simplayer here")
                # if(self.createSimulationTab.simPlayer.movie != ""):  issues where movie doesn't exist.  
                #    self.createSimulationTab.simPlayer.Stop()
    
    def OnManageNotebookPageChanged(self, event):
        if(self.manageNotebook.IsShown() == True):
            if(self.manageNotebook.GetSelection() == 0): # layout resources
                self.DisplayDebug("do stuff on load if needed and when tab changes...")
            elif(self.manageNotebook.GetSelection() == 1): # course look feel tab
                self.DisplayDebug("course look feel here...")

    # Create Event Function
    def NewCourse(self, event):
        newCourseDialog = wx.TextEntryDialog(self, "", "Enter the Course Title")

        if (newCourseDialog.ShowModal() == wx.ID_OK):
            if (self.GetTitle() == "WomBaT Development Framework"):
                self.toolbar.EnableTool(self.toolbar_CREATE_COURSE, True) # course not open, enable course buttons...
                self.toolbar.EnableTool(self.toolbar_MANAGE_COURSE, True)
                self.toolbar.EnableTool(self.toolbar_PREVIEW_COURSE, True)
                self.toolbar.EnableTool(self.toolbar_PUBLISH_COURSE, True)
            
            self.toolbar.EnableTool(wx.ID_OPEN, True) # set open course to true since a course exists now
            con = sqlite3.connect(self.database)
            cur = con.cursor()
            cur.execute("INSERT INTO CourseTable (courseName) VALUES(?)", (newCourseDialog.GetValue(),))
            self.currentCourseID = cur.lastrowid
            con.commit()
            con.close()
            self.SetTitle("WomBaT - %s" % newCourseDialog.GetValue())
            self.createContentTab.createContentRichTextCtrl.Clear()
            self.currentContentDict = self.RefreshListBox(self.createContentTab.listBox, self.currentCourseID, 1, None)
            self.RefreshModuleListBox(self.layoutContentTab.moduleListBox, self.currentCourseID)
            self.currentImageDict = self.RefreshListBox(self.createImageTab.imageListBox, self.currentCourseID, 2, None)
            self.currentTableDict = self.RefreshListBox(self.createTableTab.tableListBox, self.currentCourseID, 3, None)
            self.currentMediaDict = self.RefreshListBox(self.createMediaTab.mediaListBox, self.currentCourseID, 4, None)
            self.currentSimulationDict = self.RefreshListBox(self.createSimulationTab.simulationListBox, self.currentCourseID, 5, None)
            self.currentInteractionDict = self.RefreshListBox(self.createInteractionTab.interactionListBox, self.currentCourseID, 6, None)
            if(self.createTableTab.gridPanel.GetChildren() != []):
                self.createTableTab.gridPanel.DestroyChildren()
            self.createImageTab.imageViewer.DestroyChildren()
            self.courseContentNotebook.SetSelection(0) # reset content tab as first tab
            self.panel.Hide() # hide panel
            # loop to untoggle page toolbar items
            for tmpId in [self.toolbar_CREATE_COURSE, self.toolbar_MANAGE_COURSE, self.toolbar_PREVIEW_COURSE, self.toolbar_PUBLISH_COURSE]:
                self.toolbar.ToggleTool(tmpId, 0)
            self.bitmap = wx.Bitmap("images/wombat_border_sm_solid.png") # set logo
            wx.EVT_PAINT(self, self.OnPaint) # display logo
        
        newCourseDialog.Destroy()
               
    # Create Event Function
    def OpenCourse(self, event):
        #get list of courseNames
        courseNameList = list()
        con = sqlite3.connect(self.database)
        cur = con.cursor()
        cur.execute("SELECT courseName from CourseTable order by courseID")
        for row in cur:
            courseNameList.append(row[0])
            
        con.close()
        openCourseDialog = wx.SingleChoiceDialog(self, "", "Choose a Course", courseNameList, wx.CHOICEDLG_STYLE)
        
        if (openCourseDialog.ShowModal() == wx.ID_OK):
            if (self.GetTitle() == "WomBaT Development Framework"): # existing course not open
                self.toolbar.EnableTool(self.toolbar_CREATE_COURSE, True)
                self.toolbar.EnableTool(self.toolbar_MANAGE_COURSE, True)
                self.toolbar.EnableTool(self.toolbar_PREVIEW_COURSE, True)
                self.toolbar.EnableTool(self.toolbar_PUBLISH_COURSE, True)
                
            self.currentCourseID = (openCourseDialog.GetSelection() + 1)
            self.currentContentDict = self.RefreshListBox(self.createContentTab.listBox, self.currentCourseID, 1, None)
            self.RefreshModuleListBox(self.layoutContentTab.moduleListBox, self.currentCourseID)
            self.currentImageDict = self.RefreshListBox(self.createImageTab.imageListBox, self.currentCourseID, 2, None)
            self.currentTableDict = self.RefreshListBox(self.createTableTab.tableListBox, self.currentCourseID, 3, None)
            self.currentMediaDict = self.RefreshListBox(self.createMediaTab.mediaListBox, self.currentCourseID, 4, None)
            self.currentSimulationDict = self.RefreshListBox(self.createSimulationTab.simulationListBox, self.currentCourseID, 5, None)
            self.currentInteractionDict = self.RefreshListBox(self.createInteractionTab.interactionListBox, self.currentCourseID, 6, None)
            # add refresh available resources list box here...
            self.createContentTab.createContentRichTextCtrl.Clear()
            if(self.createTableTab.gridPanel.GetChildren() != []):
                self.createTableTab.gridPanel.DestroyChildren()
            self.createImageTab.imageViewer.DestroyChildren()
            if(self.createMediaTab.mediaPanel.GetChildren() != []):
                self.createMediaTab.mediaPanel.DestroyChildren()
            self.SetTitle("WomBaT - %s" % openCourseDialog.GetStringSelection())
            self.courseContentNotebook.SetSelection(0) # reset content tab as first tab
            self.panel.Hide() # hide panel
            # loop to untoggle page toolbar items
            for tmpId in [self.toolbar_CREATE_COURSE, self.toolbar_MANAGE_COURSE, self.toolbar_PREVIEW_COURSE, self.toolbar_PUBLISH_COURSE]:
                self.toolbar.ToggleTool(tmpId, 0)
            self.bitmap = wx.Bitmap("images/wombat_border_sm_solid.png") # set logo
            wx.EVT_PAINT(self, self.OnPaint) # display logo
            
        openCourseDialog.Destroy()
        

    # Create Event Function
    def _onSize(self, event):
        event.Skip()
        self.managePanel.SetSize(self.GetClientSizeTuple())
        self.courseContentPanel.SetSize(self.GetClientSizeTuple())
    
    # Create Event Function    
    def OnPaint(self, event):
        dc = wx.PaintDC(self)
        dc.DrawBitmap(self.bitmap, 10, 40) # backdrop logo - hidden for now.

    # Create Event Function    
    def OnTimeToClose(self, evt):
        delPath = self.TopLevelParent.GetAppPath() + "/tmpMedia.*"
        tmpFileList = glob.glob(delPath)
        for tmpFile in tmpFileList:
            os.remove(tmpFile)
            self.DisplayDebug(tmpFile + " removed")
        
        self.Destroy()
        
        
    # Create Event Function
    def SetMode(self, evt):
        for tmpId in [self.toolbar_CREATE_COURSE, self.toolbar_MANAGE_COURSE, self.toolbar_PREVIEW_COURSE, self.toolbar_PUBLISH_COURSE]:
            self.toolbar.ToggleTool(tmpId, 0)
        self.toolbar.ToggleTool(evt.GetId(), 1)
        self.panel.Show()
        if evt.GetId() == self.toolbar_CREATE_COURSE:
            self.managePanel.Hide()
            self.previewPanel.Hide()
            self.courseContentPanel.Show()
        elif evt.GetId() == self.toolbar_MANAGE_COURSE:
            self.courseContentPanel.Hide()
            self.previewPanel.Hide()
            self.currentAvailableResourceDict = self.RefreshListBox(self.layoutContentTab.availableResourcesListBox, self.currentCourseID, -1, -1)
            self.managePanel.Show()
        elif evt.GetId() == self.toolbar_PREVIEW_COURSE:
            self.managePanel.Hide()
            self.courseContentPanel.Hide()
            self.previewPanel.Show()
            
            
    def GetStructureID(self, structureOrderNumber, structureTypeID, curCourseID):
        con2 = sqlite3.connect(self.database)
        cursor = con2.cursor()
        cursor.execute("SELECT structureID from StructureTable where courseID = (?) and structureTypeID = (?) and structureOrderNumber = (?)", (curCourseID, structureTypeID, structureOrderNumber))
        for row in cursor:
            tmpValue = row[0]
        con2.close()
        
        return tmpValue

    def getText(self, nodelist):
        rc = ""
        for node in nodelist:
            if node.nodeType == node.TEXT_NODE:
                rc = rc + node.data
        return rc
    
    def RefreshListBox(self, currentListBox, curCourseID, curResourceTypeID, curStructureID):
        # currently not using the tempDict to access resourceID since the resourceData can be equal...
        # for respective if statements that are on a page...
        currentListBox.Clear() # clear listbox
        resourceIncrement = 0; # set increment variable
        tmpDict = {} # initialize temp dictionary to return
        noResource = 0 # set noresource variable
        con = sqlite3.connect(self.database)
        cur = con.cursor()
        cur2 = con.cursor()
        if(curStructureID is None):
            if (curResourceTypeID != -1): # all specific resources for a course
                cur.execute("SELECT resourceData, resourceID, layout, resourceTypeID from ResourceTable where courseID = (?) and resourceTypeID = (?)", (curCourseID, curResourceTypeID))
        else:
            
            if (curResourceTypeID == -1) and (curStructureID == -1): # all available resources for a course (content, images, etc)
                cur.execute("SELECT resourceData, resourceID, layout, resourceTypeID from ResourceTable where courseID = (?) and structureID IS NULL", (curCourseID,))
            
            elif (curResourceTypeID == -1) and (curStructureID != -1): # all resources on a page (content, images, etc) 
                cur.execute("SELECT resourceData, resourceID, layout, resourceTypeID from ResourceTable where courseID = (?) and structureID = (?) order by resourceOrderNumber", (curCourseID, curStructureID))
                
            elif (curResourceTypeID != -1) and (curStructureID == -1): # specific available resources for a course(content or images or etc)
                cur.execute("SELECT resourceData, resourceID, layout, resourceTypeID from ResourceTable where courseID = (?) and resourceTypeID = (?) and structureID IS NULL", (curCourseID, curResourceTypeID))
                
            elif (curResourceTypeID != -1) and (curStructureID != -1): # specific resources on a page for a course
                # the above elif may not be needed since it would be for editing content on a page, which isn't implemented yet or won't be implemented
                cur.execute("SELECT resourceData, resourceID, layout, resourceTypeID from ResourceTable where courseID = (?) and resourceTypeID = (?) and structureID = (?)", (curCourseID, curResourceTypeID, curStructureID))

        for row in cur:
            if(curStructureID is not None): # all resources on a page that are re-ordered accordingly...
                if(curResourceTypeID == -1) and (curStructureID != -1):
                    cur2.execute("UPDATE ResourceTable set resourceOrderNumber = (?) where courseID = (?) and resourceID = (?)", (resourceIncrement,curCourseID, row[1]))
                    resourceIncrement = resourceIncrement + 1
            
            if(curResourceTypeID == -1):
                if(row[3] == 1): # content type
                    tmpDict.setdefault(row[1],[]).append(str(row[0])) # add item (id, data)
                    tmpText = ""
                    resourceDoc = parseString(row[0])
                    textElements = resourceDoc.getElementsByTagName("text")
                    for text in textElements:
                        tmpText += self.getText(text.childNodes) # get unformatted text for listbox
                        
                elif (row[3] == 2): # image type
                    tmpDict.setdefault(row[1],[]).append(str(row[0])) # add item (id, data)
                    tmpText = ""
                    layoutTextList = str(row[2]).split("::") # get/split layout
                    tmpText = layoutTextList[1] # layout image title
                elif(row[3] == 3): # table type
                    tmpDict.setdefault(row[1],[]).append(str(row[0])) #add item (id, data)
                    tmpText = ""
                    layoutTextList = str(row[2]).split("::") # get/split layout
                    tmpText = layoutTextList[1] # layout table caption
                elif(row[3] == 4): # media type
                    tmpDict.setdefault(row[1],[]).append(str(row[0])) # add item (id, data)
                    tmpText = ""
                    layoutTextList = str(row[2]).split("::") # get/split layout
                    tmpText = layoutTextList[1] # layout media title
                elif(row[3] == 5): # simulation type
                    tmpDict.setdefault(row[1],[]).append(str(row[0])) # add item (id, data)
                    tmpText = ""
                    layoutTextList = str(row[2]).split("::") # get/split layout
                    tmpText = layoutTextList[1] # layout sim title
                elif(row[3] == 6): # interaction type
                    tmpDict.setdefault(row[1],[]).append(str(row[0])) # add item (id, data)
                    tmpText = ""
                    layoutTextList = str(row[2]).split("::") # get/split layout
                    tmpText = layoutTextList[1] # layout interaction title
                else:
                    noResource = 1
            
            elif(curResourceTypeID == 1): # set current content item...
                tmpDict.setdefault(row[1],[]).append(str(row[0])) # add item (id, data)
                tmpText = ""
                resourceDoc = parseString(row[0])
                textElements = resourceDoc.getElementsByTagName("text")
                for text in textElements:
                    tmpText += self.getText(text.childNodes) # get unformatted text for listbox
            
            elif(curResourceTypeID == 2): # set current image item...
                tmpDict.setdefault(row[1],[]).append(str(row[0])) # add item (id, data)
                tmpText = ""
                layoutTextList = str(row[2]).split("::") #get/split layout
                tmpText = layoutTextList[1] # layout image title
                
            elif(curResourceTypeID == 3): # set current table item...
                tmpDict.setdefault(row[1], []).append(str(row[0])) # add item (id, data)
                tmpText = ""
                layoutTextList = str(row[2]).split("::") # get/split layout
                tmpText = layoutTextList[1] # layout table caption
                
            elif(curResourceTypeID == 4): # set current media item
                tmpDict.setdefault(row[1],[]).append(str(row[0])) # add item (id, data)
                tmpText = ""
                layoutTextList = str(row[2]).split("::") # get/split layout
                tmpText = layoutTextList[1] # set current media item
                
            elif(curResourceTypeID == 5): # set current sim item
                tmpDict.setdefault(row[1],[]).append(str(row[0])) # add item (id, data)
                tmpText = ""
                layoutTextList = str(row[2]).split("::") # get/split layout
                tmpText = layoutTextList[1] # set current sim item
            elif(curResourceTypeID == 6): # interaction type
                tmpDict.setdefault(row[1],[]).append(str(row[0])) # add item (id, data)
                tmpText = ""
                layoutTextList = str(row[2]).split("::") # get/split layout
                tmpText = layoutTextList[1] # layout interaction title
            if(noResource != 1): # if its a resource, add to listbox
                currentListBox.Append(str(row[1]) + ". " + tmpText) # append listbox item with [id. text, caption, title]
        con.commit()
        con.close()
        
        return tmpDict # return temp dict for use
    
    def RefreshModuleListBox(self, currentListBox, curCourseID):
        currentListBox.Clear()
        moduleIncrement = 0
        con = sqlite3.connect(self.database)
        cur = con.cursor()
        cur2 = con.cursor()
        cur.execute("SELECT structureName, structureID from StructureTable where courseID = (?) and structureTypeID = 1 order by structureOrderNumber", (curCourseID,))
        for row in cur:
            currentListBox.Append(row[0])
            cur2.execute("UPDATE StructureTable set structureOrderNumber = (?) where courseID = (?) and structureID = (?)", (moduleIncrement, curCourseID, row[1]))
            moduleIncrement = moduleIncrement + 1
            
        con.commit()
        con.close()        
    
    def RefreshPageListBox(self, currentListBox, curCourseID, curModuleID):
        currentListBox.Clear()
        pageIncrement = 0
        con = sqlite3.connect(self.database)
        cur = con.cursor()
        cur2 = con.cursor()
        cur.execute("SELECT structureName, structureID from StructureTable where courseID = (?) and structureTypeID = 2 and parentID = (?) order by structureOrderNumber", (curCourseID, curModuleID))
        for row in cur:
            currentListBox.Append(row[0])
            cur2.execute("UPDATE StructureTable set structureOrderNumber = (?) where courseID = (?) and structureID = (?)", (pageIncrement, curCourseID, row[1]))
            pageIncrement = pageIncrement + 1
            
        con.commit()
        con.close()
        
    def opj(self, path):
        """Convert paths to the platform-specific separator"""
        st = apply(os.path.join, tuple(path.split('/')))
        # HACK: on Linux, a leading / gets lost...
        if path.startswith('/'):
            st = '/' + st
        return st        
    
    def GetAppPath(self):
        '''Get the path to this script no matter how it's run.'''
        #Determine if the application is a py/pyw or a frozen exe.
        if hasattr(sys, 'frozen'):
            # If run from exe
            appPath = os.path.dirname(sys.executable)
        elif '__file__' in locals():
            # If run from py
            appPath = os.path.dirname(__file__)
        else:
            # If run from command line
            appPath = sys.path[0]
        return appPath
    
    def DisplayError(self, currentErrorTitle, currentErrorText):
        self.DisplayDebug("display error to user")
        tmpErrorDialog = wx.MessageDialog(self, currentErrorText, currentErrorTitle, wx.OK | wx.ICON_ERROR)
        tmpErrorDialog.ShowModal()
        tmpErrorDialog.Destroy()
        
    def DisplayDebug(self, debugMessage):
        if(self.debugMode == True):
            print debugMessage